﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using MultiDAQ_Analysis.Util;
using MultiDAQ_Analysis.Model;

namespace MultiDAQ_Analysis.View
{
    public partial class DeviceSettingsForm : UIForm
    {
        private List<ChannelData> channelDataList;
        private int channelCount;
        private UdpProtocolSender udpSender;

        public DeviceSettingsForm()
        {
            InitializeComponent();
            channelCount = AppConfig.ChannelCount;
            udpSender = MainForm.getUdpSender();
            //InitializeUdpSender();
            LoadSettings();
            btnOK.Click += (s, e) => SaveSettings();
        }




        public string[,] ThresholdMatrix
        {
            get
            {
                int row = txtThresholds.GetLength(0);
                int col = txtThresholds.GetLength(1);
                var data = new string[row, col];
                for (int r = 0; r < row; r++)
                    for (int c = 0; c < col; c++)
                        data[r, c] = txtThresholds[r, c].Text.Trim();
                return data;
            }
        }

        // 获取起征线数据
        public double[] GetTriggerLines()
        {
            var data = new double[channelCount];
            for (int c = 0; c < channelCount; c++)
            {
                if (double.TryParse(txtTriggerLines[c].Text, out double value))
                    data[c] = value;
            }
            return data;
        }

        // 获取通道选择状态
        public bool[] GetChannelSelections()
        {
            var data = new bool[channelCount];
            for (int c = 0; c < channelCount; c++)
            {
                data[c] = chkChannelSelections[c].Checked;
            }
            return data;
        }

        // 获取步长配置（每个通道的步长）
        public double[] GetStepLengths()
        {
            var data = new double[channelCount];
            for (int c = 0; c < channelCount; c++)
            {
                if (double.TryParse(txtStepLength.Text, out double value))
                    data[c] = value;
                else
                    data[c] = channelDataList[c].StepLength;
            }
            return data;
        }

        // 获取全局步长配置
        public double GetStepLength()
        {
            if (double.TryParse(txtStepLength.Text, out double value))
                return value;
            return 1.0;
        }

        private void LoadSettings()
        {
            try
            {
                // 从文件加载所有通道数据
                channelDataList = ChannelDataManager.LoadAllChannelData();

                // 确保有足够的通道数据
                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }

                // 将数据填充到界面控件
                for (int c = 0; c < channelCount && c < txtThresholds.GetLength(1); c++)
                {
                    var channelData = channelDataList[c];

                    // 阈值数据
                    txtThresholds[0, c].Text = channelData.Thresholds.AlphaLow.ToString("0.###");
                    txtThresholds[1, c].Text = channelData.Thresholds.AlphaHigh.ToString("0.###");
                    txtThresholds[2, c].Text = channelData.Thresholds.BetaLow.ToString("0.###");
                    txtThresholds[3, c].Text = channelData.Thresholds.BetaHigh.ToString("0.###");

                    // 起征线数据（从ThresholdData中获取）
                    txtTriggerLines[c].Text = channelData.Thresholds.TriggerLine.ToString("0.###");

                    // 通道选择状态（从ThresholdData中获取）
                    chkChannelSelections[c].Checked = channelData.Thresholds.IsSelected;
                }

                // 加载 （使用第一个通道的步长作为全局显示）
                if (channelDataList.Count > 0)
                {
                    txtStepLength.Text = channelDataList[0].StepLength.ToString("0.###");
                }
                else
                {
                    txtStepLength.Text = "1.0";
                }
            }
            catch (Exception ex)
            {
                ShowCompactError($"加载设置失败：{ex.Message}");
                InitializeDefaultData();
            }
        }

        private void InitializeDefaultData()
        {
            channelDataList = new List<ChannelData>();
            for (int i = 0; i < channelCount; i++)
            {
                var channelData = new ChannelData
                {
                    ChannelIndex = i,
                    StepLength = 1.0
                };
                channelData.Thresholds.TriggerLine = 100.0;
                channelData.Thresholds.IsSelected = true;

                channelDataList.Add(channelData);
            }
        }

        private void SaveSettings()
        {
            try
            {
                // 验证输入数据
                if (!ValidateInputs())
                    return;

                // 获取步长值（所有通道使用相同的步长）
                double stepLengthValue = GetStepLength();
                // 收集需要发送UDP协议的数据
                var selectedChannels = new List<byte>();
                var betaLowValues = new Dictionary<byte, double>();
                var betaHighValues = new Dictionary<byte, double>();
                var lowerLimitValues = new Dictionary<byte, double>();
                var alphaHighValues = new Dictionary<byte, double>();  // 新增：α高阈值字典
                // 从界面控件获取数据并更新到模型
                for (int c = 0; c < channelCount && c < txtThresholds.GetLength(1); c++)
                {
                    var channelData = channelDataList[c];

                    // 更新最后修改时间
                    channelData.LastModified = DateTime.Now;

                    // 保存步长配置到每个通道
                    channelData.StepLength = stepLengthValue;

                    // 保存阈值数据
                    if (double.TryParse(txtThresholds[0, c].Text, out double alphaLow))
                        channelData.Thresholds.AlphaLow = alphaLow;

                    if (double.TryParse(txtThresholds[1, c].Text, out double alphaHigh))
                        channelData.Thresholds.AlphaHigh = alphaHigh;

                    if (double.TryParse(txtThresholds[2, c].Text, out double betaLow))
                        channelData.Thresholds.BetaLow = betaLow;

                    if (double.TryParse(txtThresholds[3, c].Text, out double betaHigh))
                        channelData.Thresholds.BetaHigh = betaHigh;

                    // 保存起征线数据到ThresholdData
                    if (double.TryParse(txtTriggerLines[c].Text, out double triggerLine))
                        channelData.Thresholds.TriggerLine = triggerLine;
                    // 如果通道被选中，准备UDP发送数据
                    if (chkChannelSelections[c].Checked)
                    {
                        byte channelNumber = (byte)(c + 1); // 通道号从1开始
                        selectedChannels.Add(channelNumber);
                        lowerLimitValues[channelNumber] = channelData.Thresholds.TriggerLine;
                        betaLowValues[channelNumber] = channelData.Thresholds.BetaLow;
                        betaHighValues[channelNumber] = channelData.Thresholds.BetaHigh;
                        alphaHighValues[channelNumber] = channelData.Thresholds.AlphaHigh;  // 新增：收集α高阈值
                    }


                    // 保存通道选择状态到ThresholdData
                    channelData.Thresholds.IsSelected = chkChannelSelections[c].Checked;
                }

                // 保存到文件
                if (ChannelDataManager.SaveAllChannelData(channelDataList))
                {
                    // 发送UDP协议数据到选中的通道
                    bool udpSendSuccess = SendAllProtocolData(selectedChannels, betaLowValues, betaHighValues, lowerLimitValues, alphaHighValues, stepLengthValue);

                    if (udpSendSuccess)
                    {
                        ShowCompactSuccess("设置保存并发送成功");
                    }
                    else
                    {
                        ShowCompactWarning("设置已保存，但UDP协议发送部分失败");
                    }

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    ShowCompactError("保存失败，请重试");
                }
            }
            catch (Exception ex)
            {
                ShowCompactError($"保存失败：{ex.Message}");
            }
        }
       

        private bool SendAllProtocolData(List<byte> selectedChannels,
    Dictionary<byte, double> betaLowValues,
    Dictionary<byte, double> betaHighValues,
    Dictionary<byte, double> lowerLimitValues,
    Dictionary<byte, double> alphaHighValues,  // 新增参数
    double stepLength)
        {
            if (udpSender == null) {
                try
                {
                    udpSender = new UdpProtocolSender();
                    udpSender.OnLogMessage += msg => Console.WriteLine($"[发送] {msg}");
                    udpSender.OnErrorMessage += err => Console.WriteLine($"[发送错误] {err}");

                }
                catch (Exception ex)
                {
                    CompactMessageBox.ShowError($"UDP发送器初始化失败:：{ex.Message}");
                }
            }

            try
            {
                bool allSuccess = true;
                int frameInterval = 50;

                System.Diagnostics.Debug.WriteLine($"开始发送UDP协议数据，选中通道数：{selectedChannels.Count}");

                // 第0阶段：发送所有选中通道的下限值 (0x03协议)
                System.Diagnostics.Debug.WriteLine("=== 第0阶段：发送所有通道的下限值 ===");
                foreach (byte channelNumber in selectedChannels)
                {
                    byte targetChannel = (byte)(channelNumber + 1); // 高阶版本映射：N → N+1

                    if (lowerLimitValues.ContainsKey(channelNumber))
                    {
                        double lowerLimit = lowerLimitValues[channelNumber];
                        bool success = udpSender.SendLowerLimit(targetChannel, lowerLimit);

                        if (success)
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} 下限值 → UDP通道{targetChannel} 发送成功: {lowerLimit:F4}V");
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} 下限值 → UDP通道{targetChannel} 发送失败");
                            allSuccess = false;
                        }

                        System.Threading.Thread.Sleep(frameInterval);
                    }
                }

                // 第1阶段：发送所有选中通道的β低阈值 (0x04协议)
                System.Diagnostics.Debug.WriteLine("=== 第1阶段：发送所有通道的β低阈值 ===");
                foreach (byte channelNumber in selectedChannels)
                {
                    byte targetChannel = (byte)(channelNumber + 1); // 高阶版本映射：N → N+1

                    if (betaLowValues.ContainsKey(channelNumber))
                    {
                        double betaLow = betaLowValues[channelNumber];
                        bool success = udpSender.SendLowThreshold(targetChannel, betaLow);

                        if (success)
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} β低阈值 → UDP通道{targetChannel} 发送成功: {betaLow:F4}V");
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} β低阈值 → UDP通道{targetChannel} 发送失败");
                            allSuccess = false;
                        }

                        System.Threading.Thread.Sleep(frameInterval);
                    }
                }

                // 第2阶段：发送所有选中通道的β高阈值 (0x05协议)
                System.Diagnostics.Debug.WriteLine("=== 第2阶段：发送所有通道的β高阈值 ===");
                foreach (byte channelNumber in selectedChannels)
                {
                    byte targetChannel = (byte)(channelNumber + 1); // 高阶版本映射：N → N+1

                    if (betaHighValues.ContainsKey(channelNumber))
                    {
                        double betaHigh = betaHighValues[channelNumber];
                        bool success = udpSender.SendHighThreshold(targetChannel, betaHigh);

                        if (success)
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} β高阈值 → UDP通道{targetChannel} 发送成功: {betaHigh:F4}V");
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} β高阈值 → UDP通道{targetChannel} 发送失败");
                            allSuccess = false;
                        }

                        System.Threading.Thread.Sleep(frameInterval);
                    }
                }

                // 第3阶段：发送所有选中通道的α高阈值 (0x08协议 - 时间谱脉宽起始阈值)
                System.Diagnostics.Debug.WriteLine("=== 第3阶段：发送所有通道的α高阈值（时间谱脉宽起始阈值）===");
                foreach (byte channelNumber in selectedChannels)
                {
                    byte targetChannel = (byte)(channelNumber + 1); // 高阶版本映射：N → N+1

                    if (alphaHighValues.ContainsKey(channelNumber))
                    {
                        double alphaHigh = alphaHighValues[channelNumber];
                        bool success = udpSender.SendPulseWidthStartThreshold(targetChannel, alphaHigh);

                        if (success)
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} α时间谱脉宽起始阈值 → UDP通道{targetChannel} 发送成功: {alphaHigh:F4}V");
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine($"界面通道{channelNumber} α时间谱脉宽起始阈值 → UDP通道{targetChannel} 发送失败");
                            allSuccess = false;
                        }

                        System.Threading.Thread.Sleep(frameInterval);
                    }
                }

                // 第4阶段：发送步长配置 (0x06 SpacedPoints)（原第3阶段）
                System.Diagnostics.Debug.WriteLine("=== 第4阶段：发送步长配置 ===");


                uint spacedPointsValue = (uint)Math.Round(stepLength / 4);
                bool stepSuccess = udpSender.SendSpacedPoints(spacedPointsValue);

                if (stepSuccess)
                {
                    System.Diagnostics.Debug.WriteLine($"步长配置发送成功: {stepLength:F4} → SpacedPoints: {spacedPointsValue}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("步长配置发送失败");
                    allSuccess = false;
                }

                System.Diagnostics.Debug.WriteLine($"=== UDP协议发送完成，整体成功：{allSuccess} ===");
                return allSuccess;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"发送协议数据异常：{ex.Message}");
                return false;
            }
        }



        private bool ValidateInputs()
        {
            // 验证阈值输入
            for (int r = 0; r < txtThresholds.GetLength(0); r++)
            {
                for (int c = 0; c < txtThresholds.GetLength(1); c++)
                {
                    if (!double.TryParse(txtThresholds[r, c].Text, out _))
                    {
                        ShowCompactError($"通道{c + 1}的阈值输入格式错误");
                        txtThresholds[r, c].Focus();
                        return false;
                    }
                }
            }

            // 验证起征线输入
            for (int c = 0; c < channelCount; c++)
            {
                if (!double.TryParse(txtTriggerLines[c].Text, out _))
                {
                    ShowCompactError($"通道{c + 1}的起征线输入格式错误");
                    txtTriggerLines[c].Focus();
                    return false;
                }
            }

            // 验证步长输入
            if (!double.TryParse(txtStepLength.Text, out double stepValue) || stepValue <= 0)
            {
                ShowCompactError("步长配置必须为正数");
                txtStepLength.Focus();
                return false;
            }

            return true;
        }
        // 小而美的成功提示 - 按钮底部居中
        private void ShowCompactSuccess(string message)
        {
            using (var form = new Form())
            {
                form.Text = "提示";
                form.Size = new Size(260, 135);
                form.StartPosition = FormStartPosition.CenterScreen;
                form.MaximizeBox = false;
                form.MinimizeBox = false;
                form.FormBorderStyle = FormBorderStyle.FixedDialog;
                form.Font = this.Font;
                form.BackColor = Color.White;

                var icon = new PictureBox
                {
                    Image = SystemIcons.Information.ToBitmap(),
                    Size = new Size(24, 24),
                    Location = new Point(20, 20),
                    SizeMode = PictureBoxSizeMode.StretchImage
                };

                var label = new Label
                {
                    Text = message,
                    Location = new Point(50, 23),
                    Size = new Size(140, 18),
                    ForeColor = Color.FromArgb(76, 175, 80),
                    Font = new Font(this.Font.FontFamily, 9, FontStyle.Regular),
                    TextAlign = ContentAlignment.MiddleLeft
                };

                var btnOk = new Button
                {
                    Text = "确定",
                    Size = new Size(60, 28),
                    // 计算居中位置：(窗体宽度 - 按钮宽度) / 2，底部留8px边距
                    Location = new Point((form.Width - 60) / 2, form.Height - 28 - 15 - 30), // 减去标题栏高度约30px
                    DialogResult = DialogResult.OK,
                    FlatStyle = FlatStyle.Flat,
                    BackColor = Color.FromArgb(76, 175, 80),
                    ForeColor = Color.White,
                    Font = new Font(this.Font.FontFamily, 8)
                };
                btnOk.FlatAppearance.BorderSize = 0;

                form.Controls.AddRange(new Control[] { icon, label, btnOk });
                form.AcceptButton = btnOk;

                // 确保窗体在最前面显示
                form.TopMost = true;
                form.ShowDialog();
                form.TopMost = false;
            }
        }

        // 小而美的警告提示
        private void ShowCompactWarning(string message)
        {
            using (var form = new Form())
            {
                form.Text = "警告";
                form.Size = new Size(260, 135);
                form.StartPosition = FormStartPosition.CenterScreen;
                form.MaximizeBox = false;
                form.MinimizeBox = false;
                form.FormBorderStyle = FormBorderStyle.FixedDialog;
                form.Font = this.Font;
                form.BackColor = Color.White;

                var icon = new PictureBox
                {
                    Image = SystemIcons.Warning.ToBitmap(),
                    Size = new Size(24, 24),
                    Location = new Point(20, 20),
                    SizeMode = PictureBoxSizeMode.StretchImage
                };

                var label = new Label
                {
                    Text = message,
                    Location = new Point(55, 15),
                    Size = new Size(220, 35),
                    ForeColor = Color.FromArgb(255, 152, 0),
                    Font = new Font(this.Font.FontFamily, 8)
                };

                var btnOk = new Button
                {
                    Text = "确定",
                    Size = new Size(60, 28),
                    Location = new Point((form.ClientSize.Width - 60) / 2, form.ClientSize.Height - 28 - 8),
                    DialogResult = DialogResult.OK,
                    FlatStyle = FlatStyle.Flat,
                    BackColor = Color.FromArgb(255, 152, 0),
                    ForeColor = Color.White,
                    Font = new Font(this.Font.FontFamily, 8),
                    Anchor = AnchorStyles.Bottom
                };
                btnOk.FlatAppearance.BorderSize = 0;

                form.Controls.AddRange(new Control[] { icon, label, btnOk });
                form.AcceptButton = btnOk;

                form.TopMost = true;
                form.ShowDialog();
                form.TopMost = false;
            }
        }
        // 小而美的错误提示 - 按钮底部居中
        private void ShowCompactError(string message)
        {
            using (var form = new Form())
            {
                form.Text = "错误";
                form.Size = new Size(280, 120);
                form.StartPosition = FormStartPosition.CenterScreen;
                form.MaximizeBox = false;
                form.MinimizeBox = false;
                form.FormBorderStyle = FormBorderStyle.FixedDialog;
                form.Font = this.Font;
                form.BackColor = Color.White;

                var icon = new PictureBox
                {
                    Image = SystemIcons.Error.ToBitmap(),
                    Size = new Size(24, 24),
                    Location = new Point(20, 20),
                    SizeMode = PictureBoxSizeMode.StretchImage
                };

                var label = new Label
                {
                    Text = message,
                    Location = new Point(55, 15),
                    Size = new Size(190, 35),
                    ForeColor = Color.FromArgb(244, 67, 54),
                    Font = new Font(this.Font.FontFamily, 8),
                    TextAlign = ContentAlignment.TopLeft
                };

                var btnOk = new Button
                {
                    Text = "确定",
                    Size = new Size(50, 23),
                    // 计算居中位置：(窗体宽度 - 按钮宽度) / 2，底部留8px边距
                    Location = new Point((form.Width - 60) / 2, form.Height - 28 - 8 - 30), // 减去标题栏高度约30px
                    DialogResult = DialogResult.OK,
                    FlatStyle = FlatStyle.Flat,
                    BackColor = Color.FromArgb(244, 67, 54),
                    ForeColor = Color.White,
                    Font = new Font(this.Font.FontFamily, 8)
                };
                btnOk.FlatAppearance.BorderSize = 0;

                form.Controls.AddRange(new Control[] { icon, label, btnOk });
                form.AcceptButton = btnOk;

                // 确保窗体在最前面显示
                form.TopMost = true;
                form.ShowDialog();
                form.TopMost = false;
            }
        }


        // 其他原有方法保持不变...
        public ThresholdData GetChannelThresholds(int channelIndex)
        {
            if (channelIndex >= 0 && channelIndex < channelDataList.Count)
            {
                return channelDataList[channelIndex].Thresholds;
            }
            return new ThresholdData();
        }

        public void SetChannelThresholds(int channelIndex, ThresholdData thresholds)
        {
            if (channelIndex >= 0 && channelIndex < channelDataList.Count)
            {
                channelDataList[channelIndex].Thresholds = thresholds;

                if (channelIndex < txtThresholds.GetLength(1))
                {
                    txtThresholds[0, channelIndex].Text = thresholds.AlphaLow.ToString("0.###");
                    txtThresholds[1, channelIndex].Text = thresholds.AlphaHigh.ToString("0.###");
                    txtThresholds[2, channelIndex].Text = thresholds.BetaLow.ToString("0.###");
                    txtThresholds[3, channelIndex].Text = thresholds.BetaHigh.ToString("0.###");

                    // 更新起征线和通道选择状态显示
                    txtTriggerLines[channelIndex].Text = thresholds.TriggerLine.ToString("0.###");
                    chkChannelSelections[channelIndex].Checked = thresholds.IsSelected;
                }
            }
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // 释放组件资源
                if (components != null)
                    components.Dispose();
            }
            base.Dispose(disposing);
        }


    }
}
